import React, { useEffect, Fragment, useRef } from 'react';
import { connect } from 'umi';
import { Form, Anchor, Result, Input, DatePicker, Select, Radio } from 'antd';
import { getOrganization } from '@/utils/utils';
import moment from 'moment';

import welcomeSrc from '@/assets/welcome.png';

import Footer from '@/layouts/Footer';
import styles from './index.less';
import Form1 from './Components/Form1';
import Form2 from './Components/Form2';
import Form3 from './Components/Form3';
import Form4 from './Components/Form4';
import { jsonFormWork, jsonFormFamily, jsonFormSchool, jsonFormTrain, jsonFormAward, map } from './jsonForm';

// const { Step } = Steps;
// const { TabPane } = Tabs;
const { Link } = Anchor;

const formItemLayout = {
    labelCol: {
        md: { span: 8 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 15 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};
const { RangePicker, MonthPicker } = DatePicker;
const { Option } = Select;

const InitUser = ({ form, user, dispatch, dictionary, loading, avatarFile }) => {
    const User = user.currentUser;
    const { entryUser } = user;
    // const [activeKey, setActiveKey] = useState('0');
    // const { resumeData, setFormFields } = useParseResume({ userCode: User.userCode, dictionary, form });
    const childRef = useRef();
    const { getFieldDecorator } = form;

    // 下一步
    // const next = key => {
    //     setActiveKey(key);
    // };

    // 表单提交
    const handleSubmit = e => {
        e.preventDefault();

        // 后端这些字段都要
        const neededKeys = [
            'serialVersionUID',
            'id',
            'orgUserId',
            'orgUserSchoolId',
            'userName',
            'employeeName',
            'email',
            'mobile',
            'userNo',
            'companyId',
            'departmentId',
            'postId',
            'roleIds',
            'timeOfEntry',
            'employeeRank',
            'teacherId',
            'inServiceStatus',
            'highestDegree',
            'sex',
            'birthday',
            'nationalArea',
            'address',
            'defaultEmployee',
            'areaCode',
            'detailAddress',
            'userCode',
            'jobDescriptions',
            'jobLabel',
            'jobLabelList',
            'idCard',
            'postCode',
            'workYear',
            'workMonth',
            'emergencyContact',
            'emergencyRelationship',
            'emergencyAreaCode',
            'emergencyTelephone',
            'workNature',
            'tryDuration',
            'agree',
            'companyName',
            // 'workExperience',

            'familyDTOList',
            'workDTOList',
            'schoolDTOList',
            'trainDTOList',
            'awardDTOList'
        ];

        form.validateFieldsAndScroll((err, values) => {
            console.log(values, 'values');
            console.log(err, 'err');
            if (!err) {
                // 家庭数据
                const familyData = [];
                if (values.familyKeys) {
                    values.familyKeys.forEach(key => {
                        const obj = {};
                        jsonFormFamily.forEach(item => {
                            obj[item.fileName.replace('family_', '')] = values[`${item.fileName}_${key}`];
                        });
                        obj.areaCode = values[`family_areaCode_${key}`]; // 因为这个区号不在判断范围内，所以单独添加
                        obj.userCode = entryUser.userCode;
                        obj.id = (entryUser.familyDTOList[key] && entryUser.familyDTOList[key].id) || null;
                        obj.deleteFlag = obj.id && values.removeFamilyIds.includes(obj.id) ? 1 : 0;
                        if (Object.keys(obj).length > 0) {
                            familyData.push(obj);
                        }
                    });
                }

                // 工作数据
                const workData = [];
                if (values.workKeys) {
                    values.workKeys.forEach(key => {
                        const obj = {};
                        jsonFormWork.forEach(item => {
                            obj.userCode = entryUser.userCode;
                            obj.id = (entryUser.workDTOList[key] && entryUser.workDTOList[key].id) || null;
                            obj.deleteFlag = obj.id && values.removeWorkIds.includes(obj.id) ? 1 : 0;
                            if (values[`${item.fileName}_${key}`] && values.workExperience === 1) {
                                if (obj.deleteFlag !== 1) {
                                    // 时间字段需要特殊处理
                                    if (
                                        item.fileName === 'work_startTime' &&
                                        values[`${item.fileName}_${key}`] &&
                                        values[`${item.fileName}_${key}`].length > 0
                                    ) {
                                        const startTime = values[`${item.fileName}_${key}`][0];
                                        const endTime = values[`${item.fileName}_${key}`][1];

                                        obj.startTime = startTime ? moment(startTime).format('YYYY-MM-01') : '';
                                        obj.endTime = endTime ? moment(endTime).format('YYYY-MM-01') : '';
                                    } else {
                                        obj[item.fileName.replace('work_', '')] = values[`${item.fileName}_${key}`];
                                    }
                                }
                            }
                        });
                        obj.areaCode = values[`work_areaCode_${key}`]; // 因为这个区号不在判断范围内，所以单独添加
                        if (Object.keys(obj).length > 0) {
                            workData.push(obj);
                        }
                    });
                }

                // 教育经历
                const schoolData = [];
                if (values.schoolKeys) {
                    values.schoolKeys.forEach(key => {
                        const obj = {};
                        jsonFormSchool.forEach(item => {
                            obj.id = (entryUser.schoolDTOList[key] && entryUser.schoolDTOList[key].id) || null;
                            obj.userCode = entryUser.userCode;
                            obj.deleteFlag = obj.id && values.removeSchoolIds.includes(obj.id) ? 1 : 0;
                            if (obj.deleteFlag !== 1) {
                                // 时间字段需要特殊处理
                                if (item.fileName === 'school_startTime') {
                                    obj.startTime = moment(values[`${item.fileName}_${key}`][0]).format('YYYY-MM-01');
                                    obj.endTime = moment(values[`${item.fileName}_${key}`][1]).format('YYYY-MM-01');
                                } else {
                                    obj[item.fileName.replace('school_', '')] = values[`${item.fileName}_${key}`];
                                }
                            }
                        });
                        if (Object.keys(obj).length > 0) {
                            schoolData.push(obj);
                        }
                    });
                }

                // 培训经历
                const trainData = [];
                if (values.trainKeys) {
                    values.trainKeys.forEach(key => {
                        const obj = {};
                        jsonFormTrain.forEach(item => {
                            obj.userCode = entryUser.userCode;
                            obj.id = (entryUser.trainDTOList[key] && entryUser.trainDTOList[key].id) || null;
                            obj.deleteFlag = obj.id && values.removeTrainIds.includes(obj.id) ? 1 : 0;
                            if (values[`${item.fileName}_${key}`]) {
                                if (obj.deleteFlag !== 1) {
                                    // 时间字段需要特殊处理
                                    if (
                                        item.fileName === 'train_startTime' &&
                                        values[`${item.fileName}_${key}`] &&
                                        values[`${item.fileName}_${key}`].length > 0
                                    ) {
                                        const startTime = values[`${item.fileName}_${key}`][0];
                                        const endTime = values[`${item.fileName}_${key}`][1];

                                        obj.startTime = startTime ? moment(startTime).format('YYYY-MM-01') : '';
                                        obj.endTime = endTime ? moment(endTime).format('YYYY-MM-01') : '';
                                    } else {
                                        obj[item.fileName.replace('train_', '')] = values[`${item.fileName}_${key}`];
                                    }
                                }
                            }
                        });
                        if (Object.keys(obj).length > 0) {
                            const { userCode: uc, id, deleteFlag, ...reset } = obj;
                            if (obj.id === null && Object.keys(reset).length === 0) {
                                return;
                            }
                            trainData.push(obj);
                        }
                    });
                }

                // 获奖记录
                const awardData = [];
                if (values.awardKeys) {
                    values.awardKeys.forEach(key => {
                        const obj = {};
                        jsonFormAward.forEach(item => {
                            obj.userCode = entryUser.userCode;
                            obj.id = (entryUser.awardDTOList[key] && entryUser.awardDTOList[key].id) || null;
                            obj.deleteFlag = obj.id && values.removeAwardIds.includes(obj.id) ? 1 : 0;
                            if (values[`${item.fileName}_${key}`]) {
                                if (obj.deleteFlag !== 1) {
                                    // 时间字段需要特殊处理
                                    if (item.fileName === 'award_awardTime' && values[`${item.fileName}_${key}`]) {
                                        obj.awardTime = moment(values[`${item.fileName}_${key}`]).format(
                                            'YYYY-MM-01 00:00:00'
                                        );
                                    } else {
                                        obj[item.fileName.replace('award_', '')] = values[`${item.fileName}_${key}`];
                                    }
                                }
                            }
                        });
                        if (Object.keys(obj).length > 0) {
                            const { userCode: uc, id, deleteFlag, ...reset } = obj;
                            if (obj.id === null && Object.keys(reset).length === 0) {
                                return;
                            }
                            awardData.push(obj);
                        }
                    });
                }
                const data = {
                    // ...values,
                    // 表单一
                    employeeName: values.employeeName,
                    sex: values.sex,
                    email: entryUser.email,
                    idCard: values.idCard,
                    // postCode: values.postCode,
                    // workYear: values.workYear,
                    // workMonth: values.workMonth,
                    nationalArea: values.nationalArea,
                    address: values.address,
                    detailAddress: values.detailAddress,
                    emergencyContact: values.emergencyContact,
                    emergencyRelationship: values.emergencyRelationship,
                    birthday: moment(values.birthday).format('YYYY-MM-DD'),
                    areaCode: values.areaCode,
                    mobile: values.mobile,
                    emergencyAreaCode: values.emergencyAreaCode,
                    emergencyTelephone: values.emergencyTelephone,
                    highestDegree: values.highestDegree,
                    firstHouseholdType: values.firstHouseholdType || '',
                    secondHouseholdType: values.secondHouseholdType || '',
                    // 表单二
                    familyDTOList: familyData,
                    workExperience: values.workExperience,
                    workDTOList: values.workExperience === 0 ? [] : workData,
                    // 表单三
                    schoolDTOList: schoolData,
                    trainDTOList: trainData,

                    // 表单四
                    awardDTOList: awardData,
                    agree: values.agree ? '1' : '0',

                    operateWay: '2',
                    id: User.id,
                    orgUserId: User.orgUserId,
                    orgUserSchoolId: User.orgUserSchoolId,
                    companyId: User.companyId,
                    postId: User.postId,
                    userCode: User.userCode,
                    timeOfEntry: User.timeOfEntry
                };

                neededKeys.forEach(key => {
                    if (!data[key]) {
                        data[key] = entryUser[key];
                    }
                });
                console.log('请求参数为', data);
                childRef.current.updateAvatar().then(() => {
                    dispatch({
                        type: 'user/fetchUpdate',
                        payload: data,
                        callback: () => {
                            dispatch({
                                type: 'user/fetchCurrent',
                                callback: () => {
                                    dispatch({
                                        type: 'user/fetchPersonalPortrait'
                                    });
                                }
                            });
                        }
                    });
                });
            }
        });
    };
    // 获取表单所需要的字典服务
    const getDict = () => {
        dispatch({
            type: 'dictionary/fetchDictionaryList',
            payload: {
                codes: [
                    'agreeType',
                    'sexType',
                    'emergencyRelationship',
                    'workMonth',
                    'workYear',
                    'liveTogether',
                    'workExperience',
                    'household',
                    'academicYear',
                    'industryType'
                ]
            }
        });
    };
    // 区号处理
    const returnDefinedAreaCode = () => (getOrganization(User.companyId)?.area === 'cn' ? '86' : '65');
    const returnAreaCode = areaCode => {
        if (areaCode === '' || areaCode === undefined) {
            return returnDefinedAreaCode();
        }
        return areaCode;
    };
    // 月份弹窗关闭事件
    const handlePanelChange = (value, fileName) => {
        form.setFieldsValue({
            [fileName]: value
        });
    };
    // 传入类型，返回组件 子组件公用
    const getComponent = (type, code, fileName, placeholder, areaCode) => {
        if (type === 'input') {
            return <Input placeholder={placeholder} />;
        }
        if (type === 'time') {
            return (
                <RangePicker
                    mode={['month', 'month']}
                    onPanelChange={value => {
                        handlePanelChange(value, fileName);
                    }}
                    format="YYYY-MM"
                />
            );
        }
        if (type === 'time2') {
            return <MonthPicker style={{ width: '100%' }} />;
        }
        if (type === 'select') {
            return (
                <Select placeholder={placeholder}>
                    {dictionary[code] &&
                        dictionary[code].map(item => (
                            <Option value={item.dictValue} key={item.dictValue}>
                                {item.dictName}
                            </Option>
                        ))}
                </Select>
            );
        }
        if (type === 'radio') {
            if (code === 'liveTogether') {
                return (
                    <Radio.Group>
                        {dictionary[code] &&
                            dictionary[code].map(item => (
                                <Radio value={item.dictValue} key={item.dictValue}>
                                    {item.dictName}
                                </Radio>
                            ))}
                    </Radio.Group>
                );
            }
            return '';
        }
        if (type === 'tel') {
            return (
                <Input
                    placeholder="请填入手机号"
                    addonBefore={getFieldDecorator(`${fileName.split('_')[0]}_areaCode_${fileName.split('_')[2]}`, {
                        initialValue: returnAreaCode(areaCode)
                    })(
                        <Select placeholder="区号" place style={{ width: 80 }}>
                            <Option value="86">+86</Option>
                            <Option value="65">+65</Option>
                        </Select>
                    )}
                />
            );
        }
        return '';
    };

    // 因为一些日期字段需要特殊处理，返回默认参数
    const returnValue = (fileName, value) => {
        if (fileName === 'work_startTime' || fileName === 'school_startTime' || fileName === 'train_startTime') {
            if (value.startTime === '' && value.endTime === '') {
                return [];
            }
            return [
                value.startTime === '' ? undefined : moment(value.startTime),
                value.endTime === '' ? undefined : moment(value.endTime)
            ];
        }
        if (fileName === 'award_awardTime') {
            return value[map[fileName]] === '' ? undefined : moment(value[map[fileName]]);
        }
        return value[map[fileName]];
    };
    // 获取arrkey
    const getArrKeys = (arr = []) => {
        const array = [];
        arr.forEach((_ele, index) => {
            array.push(index);
        });
        return array;
    };
    const renderTabsPage = () => (
        <Fragment>
            <div className={styles.positIon}>
                <div className={styles.fLeft}>
                    <Form layout="horizontal" {...formItemLayout} onSubmit={handleSubmit}>
                        <span id="form1">
                            <Form1
                                ref={childRef}
                                childRef={childRef}
                                form={form}
                                dict={dictionary}
                                user={User}
                                entryUser={user.entryUser}
                                dispatch={dispatch}
                                avatarFile={avatarFile}
                            />
                        </span>
                        <span id="form2">
                            <Form2
                                form={form}
                                getComponent={getComponent}
                                entryUser={user.entryUser}
                                returnValue={returnValue}
                                getArrKeys={getArrKeys}
                            />
                        </span>
                        <span id="form3">
                            <Form3
                                form={form}
                                getComponent={getComponent}
                                entryUser={user.entryUser}
                                returnValue={returnValue}
                                getArrKeys={getArrKeys}
                            />
                        </span>
                        <span id="form4">
                            <Form4
                                id="form4"
                                form={form}
                                getComponent={getComponent}
                                entryUser={user.entryUser}
                                returnValue={returnValue}
                                getArrKeys={getArrKeys}
                                loading={loading}
                            />
                        </span>
                    </Form>
                </div>
                <div className={styles.fRight}>
                    <Anchor getContainer={() => document.getElementById('scrollLayout') || window} offsetTop={150}>
                        <Link href="#form1" title="个人信息" />
                        <Link href="#form1-2" title="紧急联系人" />
                        <Link href="#form2" title="家庭信息" />
                        <Link href="#form2-2" title="工作经历" />
                        <Link href="#form3-1" title="教育经历" />
                        <Link href="#form3-2" title="培训经历" />
                        <Link href="#form4-1" title="获奖记录" />
                    </Anchor>
                </div>
            </div>
        </Fragment>
    );
    const renderWaitPage = () => (
        <Result status="success" title="提交成功" subTitle="正在等待人事部门审核，审核通过后，将发送邮件通知…" />
    );

    useEffect(() => {
        getDict();
    }, []);

    useEffect(() => {
        if (User.code) {
            dispatch({
                type: 'user/fetchEntryUser',
                payload: { userCode: User.userCode }
            });
        }
    }, [User.code]);

    // useEffect(() => {
    //     const fieldMap = {
    //         employeeName: 'employeeName',
    //         sex: 'sex',
    //         birthdayDate: 'birthday',
    //         mobile: 'mobile',
    //         idCard: 'idCard',
    //         postCode: 'postCode',
    //         highestDegree: 'highestDegree'
    //     };
    //     setFormFields(fieldMap);
    // }, [resumeData]);

    return (
        <div className={styles.scrollLayout} id="scrollLayout">
            <div className={styles.welcome}>
                <img src={welcomeSrc} alt="欢迎加入微微科技" />
            </div>
            <div className={styles.InitUserCard}>{User.code === 20012 ? renderTabsPage() : renderWaitPage()}</div>
            <Footer />
        </div>
    );
};
export default connect(({ loading, user, dictionary }) => ({
    loading,
    user,
    dictionary,
    avatarFile: user.avatarFile
}))(Form.create()(InitUser));
